from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from .x23uscom import *
from .spider import Spider
from .download import *
from .zipFild import *
import os
# Create your views here.
def all(request):
    return render(request,'novel/all.html')
def novel_index(request):
    return render(request,'novel/index.html')

def search(request):
    
    key_word = request.GET['key_word']
    
    res_obj = X23usCom(key_word)
    test = res_obj.index()
    book_info = res_obj.info()
    #print(book_info)
    for i in book_info.values():
        #print(i)
        url_id = i['url'].split('/')[1]
        book_url = 'https://www.x23us.com/book/{}'.format(url_id)
        img_url_html = requests.get(book_url).text
        img_re = '<img style="padding:7px; border:1px solid #E4E4E4; width:120px; height:150px; margin:0 25px 0 15px;" alt=".*?" src="(.*?)"  onerror=".*?"/>'
        img_url = re.findall(img_re,img_url_html)
        i['img'] = img_url[0]
        #print(i)

        #print(img_url)

    if isinstance(test,(dict,)):
        url = test['url']
        chapter = Spider(url)
        info = chapter.info(chapter_url = '<a class="read" href="https://www.x23us.com/html/(.*?)" title=".*?">章节列表</a>')
        #print(info)
        arg = info['chapter_url'][0].split('/')
        #print(arg)
        return HttpResponseRedirect(reverse('novel:book',args=(arg[0],arg[1])))

    else:
        
        context = {'info':book_info}
        #print(context)
        return render(request,'novel/search.html',context)


def book(request,book_pk,book_id):

    url = 'https://www.x23us.com/html/{}/{}'.format(book_pk,book_id)

    book_name = '<meta name="og:novel:book_name" content="(.*?)"/>'
    book_author = '<meta name="og:novel:author" content="(.*?)"/>'
    book_info = '<td class="L"><a href="(.*?)">(.*?)</a></td>'

    x = Spider(url=url)
    info_list = x.info(book_name = book_name,
                       book_author = book_author,
                       book_info = book_info,
                       )
    #print(info_list)
    
    #for page_id in range(int(round(len(info_list['book_info'])/20))):
        
        
    return render(request,'novel/book.html',context=info_list)

    
def chapter(request,book_pk,book_id,chapter_id):
    
    url = 'https://www.x23us.com/html/{}/{}/{}.html'.format(book_pk,book_id,chapter_id)

    chapter_title = '<title>(.*?)</title>'
    chapter_content = '<dd id="contents">(.*)'

    previou_page = '<dd id="footlink"><a href="/html/(.*?)">上一页</a>\
<a href="/html/(.*?)" title=".*?">返回章节列表</a>\
<a href="/html/(.*?)">下一页</a></dd>'
    #next_page = '<a href="(.*?)">下一页</a>'

    x = Spider(url=url)
    info_list = x.info(chapter_title = chapter_title,
                       chapter_content = chapter_content,
                       previou_page = previou_page,
                       #next_page = next_page,
                       
                       )
    #print(info_list)

    return render(request,'novel/chapter.html',context = info_list)

    
def download(request):
    url_s = request.GET['url']
    novel = Novel(catalog_url = 'https://www.x23us.com/html/'+url_s)
    txt_name = novel.save_paper()
    zip_name= txt_name.replace('txt','zip')
    #print(zip_name)
    cwd = os.getcwd()
    #print(cwd)
    new_cwd = cwd+'\\'+'novel\static\\'+zip_name
    #print(new_cwd)
    try:
        os.remove(new_cwd)
    except FileNotFoundError:
        z= zipfile.ZipFile(zip_name,'w',zipfile.ZIP_STORED)
        z.write(txt_name)
        z.close()
        os.rename(zip_name, new_cwd)
        content = {'name':zip_name}
        os.remove(txt_name)
        return render(request,'novel/download.html',content)
    else:
        z= zipfile.ZipFile(zip_name,'w',zipfile.ZIP_STORED)
        z.write(txt_name)
        z.close()
        os.rename(zip_name,new_cwd)
        content = {'name':zip_name}
        os.remove(txt_name)
        return render(request,'novel/download.html',content)
    #print(url_s)
    return render(request,'novel/download.html',content)
    

    

    
